package com.zerui.manager.icc.conf;

import com.dahuatech.icc.exception.ClientException;
import com.dahuatech.icc.oauth.http.DefaultClient;
import com.dahuatech.icc.oauth.http.IClient;
import com.zerui.manager.icc.properties.ICCProperties;
import com.zerui.manager.icc.service.AccessControlInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.servlet.Filter;

/**
 * ICC平台对接配置类
 *
 * @author Bing
 * @since 2023-9-17
 */
@Slf4j
@ConditionalOnProperty(value = "icc.enable", havingValue = "true", matchIfMissing = true)
@Configuration
@EnableConfigurationProperties(ICCProperties.class)
public class ICCConfiguration {

	@Resource
	private ICCProperties iccProperties;
	@Resource
	private AccessControlInfoService accessControlInfoService;

	@Bean
	public ICCOAuthConfigHolder iccOAuthConfigHolder() {
		return new ICCOAuthConfigHolder();
	}

	@Bean
	public FilterRegistrationBean<Filter> iccForwardFilterRegistrationBean(IClient iccClient, ICCProperties iccProperties) {
		ICCUrlForwardFilter filter = new ICCUrlForwardFilter(iccClient, iccProperties);
		FilterRegistrationBean filterFactoryBean = new FilterRegistrationBean();
		filterFactoryBean.setFilter(filter);
		return filterFactoryBean;
	}

	@Bean
	public IClient iccClient(ICCProperties iccProperties) throws ClientException {
		return new DefaultClient(iccProperties.getHost(), iccProperties.getClientId(), iccProperties.getClientSecret());
	}

	// 销毁前，要把订阅取消掉
	@PreDestroy
	public void cancelSubscribe() {
		try {
			accessControlInfoService.cancelSubscribe(iccProperties.getCallbackClientId());
			log.info("已取消ICC订阅事件.");
		} catch (Exception e) {
			log.error("取消订阅ICC报警事件出错", e);
		}
	}
}
